import { createAxiosInstance } from '@x-tech/fe-puma-lib-http/dist/index';
import store from '@/store/index.ts';
import router from '@/router';
import { logOff } from '@/api/login';
import { message } from '@/utils/resetMessage';
import { jsonlint } from '@/utils/jsonlint.js';

const isLocal = window.XCConfig.VUE_APP_ENV === 'local';
const $http = createAxiosInstance({
    config: {
        baseURL: window.XCConfig.VITE_URL,
    },
    successCodes: ['000', '1000', '10000', 0],
    getToken: () => {
        if (store.state.puma.token) {
            const { accessToken } = JSON.parse(store.state.puma.token);
            return accessToken || '';
        }
        return '';
    },
    logout: async () => {
        console.log('退出');
        await logOff();
        store.commit('puma/RESET_TOKEN');
        store.commit('puma/SET_USER', { username: '' });
        store.commit('app/setGlobalWaterMark', false);
        router.replace('/login');
    },
});
$http.interceptors.request.use(
    (config: any) => {
        config.transformResponse = [
            function (data: any) {
                try {
                    return jsonlint.parse(data); // 解决long精度丢失问题
                } catch (e) {
                    console.warn(e);
                    return {};
                }
            },
        ];
        return config;
    },
    (error: any) => {
        return Promise.reject(error);
    }
);

$http.interceptors.response.use(
    (response: Object) => response,
    async (error: any) => {
        const responseStatus: number = error?.response?.status;
        const statusCode: number = +error.code;
        if (responseStatus === 401 || [401, 7].includes(statusCode)) {
            // TODO 根据不同的环境执行不同操作
            store.commit('puma/' + 'SET_TOKEN', '');
            message({
                message: '暂无权限',
                type: 'error',
                duration: 5 * 1000,
            });
            await logOff();
            store.commit('puma/RESET_TOKEN');
            store.commit('puma/SET_USER', { username: '' });
            store.commit('app/setGlobalWaterMark', false);
            store.commit('app/setLoginLoading', false);
            router.replace('/login');
        } else {
            message({
                message: error.msg || error.message || '系统异常',
                type: 'error',
                duration: 5 * 1000,
            });
        }
        return Promise.reject(error);
    }
);

const simple$http = createAxiosInstance({
    config: {
        baseURL: isLocal ? '' : window.XCConfig.VITE_URL, // window.XCConfig.VUE_APP_URL,
    },
});
export { $http, simple$http };
